/*
  学习目标：发表功能
    1. 受控组件改造
    2. 完成发表功能
*/
import React from 'react';
import './index.css';

export default class App extends React.Component {
  state = {
    username: '',
    content: '',

    list: [
      {
        id: 1,
        username: '思聪',
        content: '想你的夜',
      },
      {
        id: 2,
        username: '马芸',
        content: '我对钱不感兴趣',
      },
      {
        id: 3,
        username: '王简林',
        content: '实现一个小目标',
      },
    ],
  };

  handleDelById = (id) => {
    const list = this.state.list.filter((item) => item.id !== id);
    this.setState({ list });
  };

  handleClear = () => {
    this.setState({ list: [] });
  };
  handleChange = (e) => {
    const { name, value } = e.target;
    this.setState({ [name]: value });
  };

  // 2.1 定义新增事件
  handleAdd = (e) => {
    const { username, content, list } = this.state;
    // 2.3 阻止默认行为
    e.preventDefault();

    // 2.4 更新list和清空表单的值
    this.setState({
      list: [{ username, content, id: Date.now() }, ...list],
      username: '',
      content: '',
    });
  };

  render() {
    const { list, username, content } = this.state;
    return (
      <div className="app">
        <form>
          <input
            // 1.3 使用name属性复用handleChange方法
            name="username"
            // 1.1 state控制表单元素的value或checked
            value={username}
            // 1.2 onChange配合setState修改数据
            onChange={this.handleChange}
            className="user"
            type="text"
            placeholder="请输入评论人"
          />
          <br />
          <textarea
            name="content"
            value={content}
            onChange={this.handleChange}
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
          />
          <br />
          <button
            // 2.2 绑定事件
            onClick={this.handleAdd}
          >
            发表评论
          </button>
          <button onClick={this.handleClear} type="button">
            清空评论
          </button>
        </form>
        {list.length ? (
          <ul>
            {list.map((item) => {
              return (
                <li key={item.id}>
                  <h3>评论人: {item.username}</h3>
                  <p>评论内容：{item.content}</p>
                  <button onClick={() => this.handleDelById(item.id)}>
                    删除
                  </button>
                </li>
              );
            })}
          </ul>
        ) : (
          <div>暂无数据</div>
        )}
      </div>
    );
  }
}
